<?php
declare (strict_types = 1);

namespace app\admin\controller\delivery;

use app\admin\traits\Actions;
use app\common\controller\Backend;
use app\common\model\delivery\CustomerGoods;
use app\common\model\delivery\Goods as GoodsModel;
use app\common\model\delivery\GoodsSpec;
use think\annotation\route\Group;
use think\annotation\route\Route;
use think\facade\Db;

#[Group("delivery/goods")]
class Goods extends Backend
{
    protected $model;

    use Actions{
        add as private _add;
        edit as private _edit;
    }

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new GoodsModel();
    }

    #[Route('GET,JSON','index')]
    public function index()
    {
        if (false === $this->request->isAjax()) {
            return $this->fetch();
        }
        if($this->request->post('selectpage')){
            $where=[];
            $where[]=['status','=','normal'];
            return $this->selectpage($where);
        }
        $this->relationField=['spec'];
        [$where, $order, $limit, $with] = $this->buildparams();
        $list = $this->model
            ->with($with)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    #[Route('GET,POST','add')]
    public function add()
    {
        if($this->request->isPost()){
            $this->callback=function ($row){
                $spec=htmlspecialchars_decode($this->request->post('row.spec'));
                if(!$spec){
                    $this->error('规格不能为空');
                }
                $spec=json_decode($spec,true);
                foreach($spec as &$v){
                    $v['goods_id']=$row->id;
                }
                (new GoodsSpec())->saveAll($spec);
            };
        }
        return $this->_add();
    }

    #[Route('GET,POST','edit')]
    public function edit()
    {
        if($this->request->isPost()){
            $this->postParams['spec']='';
            return $this->_edit();
        }else{
            $ids = $this->request->get('ids');
            $row = GoodsModel::with(['spec'])->find($ids);
            $this->assign('row', $row);
            return $this->fetch();
        }
    }

    #[Route('GET,JSON','setSpec')]
    public function setSpec()
    {
        $goods_id=$this->request->get('goods_id');
        if($this->request->isAjax()){
            $oldSpec=GoodsSpec::where('goods_id',$goods_id)->select();
            $spec=$this->request->post();
            $add=[];
            $edit=[];
            $delete=[];
            foreach ($spec as $v){
                $v['goods_id']=$goods_id;
                if(isset($v['id'])){
                    $edit[]=$v;
                }else{
                    $add[]=$v;
                }
            }
            foreach ($oldSpec as $old){
                $isdelete=true;
                foreach ($spec as &$v){
                    $v['goods_id']=$goods_id;
                    if(isset($v['id']) && $v['id']==$old->id){
                        $isdelete=false;
                        break;
                    }
                }
                if($isdelete){
                    $delete[]=$old->id;
                    $prefix=getDbPrefix();
                    $count=CustomerGoods::where(['goods_id'=>$goods_id,'spec_id'=>$old->id])->whereRaw("customer_id in (select id from {$prefix}customer where status='normal')")->count();
                    if($count>0){
                        $this->error('规格【'.$old['name'].'】已有客户使用，不能删除');
                    }
                }
            }
            Db::startTrans();
            try {
                if(!empty($add)){
                    (new GoodsSpec())->saveAll($add);
                }
                if(!empty($edit)){
                    (new GoodsSpec())->saveAll($edit);
                }
                if($delete){
                    GoodsSpec::whereIn('id',$delete)->delete();
                }
                Db::commit();
                $this->success('保存成功');
            }catch (\Exception $e){
                Db::rollback();
                $this->error('保存失败');
            }
            exit;
        }
        $list=GoodsSpec::where('goods_id',$goods_id)->select();
        $this->assign('list',$list);
        return $this->fetch();
    }
}
